package com.ruoyi.goods.controller;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.goods.domain.TbContent;
import com.ruoyi.goods.service.ITbContentService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 广告信息管理Controller
 * 
 * @author ruoyi
 * @date 2024-10-22
 */
@RestController
@RequestMapping("/content")
public class TbContentController extends BaseController
{
    @Autowired
    private ITbContentService tbContentService;

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.secretAccessKey}")
    private String secretAccessKey;

    /**
     * 查询广告信息管理列表
     */
    @RequiresPermissions("content:content:list")
    @GetMapping("/list")
    public TableDataInfo list(TbContent tbContent)
    {
        startPage();
        List<TbContent> list = tbContentService.selectTbContentList(tbContent);
        return getDataTable(list);
    }

    /**
     * 导出广告信息管理列表
     */
    @RequiresPermissions("content:content:export")
    @Log(title = "广告信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbContent tbContent)
    {
        List<TbContent> list = tbContentService.selectTbContentList(tbContent);
        ExcelUtil<TbContent> util = new ExcelUtil<TbContent>(TbContent.class);
        util.exportExcel(response, list, "广告信息管理数据");
    }

    /**
     * 获取广告信息管理详细信息
     */
    @RequiresPermissions("content:content:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tbContentService.selectTbContentById(id));
    }

    /**
     * 新增广告信息管理
     */
    @RequiresPermissions("content:content:add")
    @Log(title = "广告信息管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbContent tbContent)
    {
        return toAjax(tbContentService.insertTbContent(tbContent));
    }

    /**
     * 修改广告信息管理
     */
    @RequiresPermissions("content:content:edit")
    @Log(title = "广告信息管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbContent tbContent)
    {
        return toAjax(tbContentService.updateTbContent(tbContent));
    }

    /**
     * 删除广告信息管理
     */
    @RequiresPermissions("content:content:remove")
    @Log(title = "广告信息管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tbContentService.deleteTbContentByIds(ids));
    }


    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) throws Exception {
        // 获取文件名
        String filename = file.getOriginalFilename();
        // 获取文件拓展名（包左不包右）
        String extName = filename.substring(filename.lastIndexOf("."));
        // 生成新的文件名
        String uuid = UUID.randomUUID().toString();
        String newFileName = uuid + extName;


        // 获取上传文件的流数据
        InputStream inputStream = file.getInputStream();

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        DefaultCredentialProvider credentialsProvider =
                CredentialsProviderFactory.newDefaultCredentialProvider(accessKeyId,secretAccessKey);
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "bw2203a";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "content/" + newFileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        String path = "https://bw2203a.oss-cn-beijing.aliyuncs.com/" + objectName;
        return success(path);
    }

    @GetMapping("/sync")
    public AjaxResult sync() throws Exception {
        //查询出所有生效的广告并且按照排序字段排列
        TbContent tbContent = new TbContent();
        tbContent.setStatus("1");
        List<TbContent> list = tbContentService.selectTbContentList(tbContent);

        //静态页 = 模板 + 数据
        Map data = new HashMap();
        data.put("list", list);

        //创建 Freemarker的核心配置类
        Configuration configuration = new Configuration();
        //设置模板所在文件夹路径
        String classPath = this.getClass().getResource("/").getPath();
        configuration.setDirectoryForTemplateLoading(new File(classPath+"templates"));
        //通过文件名获取模板文件
        Template template = configuration.getTemplate("banner.ftl");
        //调用 Jar中的工具类合成页面代码
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);

        //将 HTML 代码写入磁盘文件
        InputStream inputStream = new ByteArrayInputStream(html.getBytes("UTF-8"));
        File outputFile = new File("/usr/local/nginx/html/banner.html");
        OutputStream outputStream = new FileOutputStream(outputFile);
        IOUtils.copy(inputStream,outputStream);

        outputStream.close();
        inputStream.close();

        return success();
    }
}
